<script setup lang="ts">
import type { VxeTableInstance } from 'vxe-table'

import { useDeleteProductOfProject, useDoPubilc, useEditProductQuantityOfProject, useExportZbTenderProject, useGetProductListOfProject, useGetProductListOfSupplier } from '@fl/api/purchase'
import { useExportCbBiddingProject } from '@fl/api/supplier'
import { SearchTable } from '@fl/components'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { formatter } from 'element-plus'
import { cloneDeep } from 'lodash-es'

import { PRICING_PROJECT_STATUS_MAP } from '../project-management/constant'
import CheckProduct from './components/check-product.vue'
import ChooseProduct from './components/choose-product.vue'

const { createConfirmModal } = useMessage()
const router = useRouter()
const route = useRoute()

const projectId = route.query.projectId as string
const supplierId = route.query.supplierId as string

const showChooseProduct = ref<boolean>(false)
const showCheckProduct = ref<boolean>(false)
const toCheckProductId = ref<string>('')

const totalPrice = ref<number>()
const isPublished = ref<boolean>(false)
const isCheckSupplier = computed(() => supplierId !== undefined)
const enableGetProductListOfProject = computed(() => !!projectId && !isCheckSupplier.value)
const getProductListOfSupplierParams = computed(() => ({
    projectId,
    supplierId,
}))

const {
    data: productListDataOfProject,
    isLoading: isGetProductListOfProjectLoading,
} = useGetProductListOfProject(projectId, enableGetProductListOfProject)
const { isPending: isEditProductQuantityOfProjectPending, mutate: editProductQuantityOfProject } = useEditProductQuantityOfProject()
const { isPending: isExportZbTenderProjectPending, mutate: exportZbTenderProject } = useExportZbTenderProject()
const { isPending: isExportCbBiddingProjectPending, mutate: exportCbBiddingProject } = useExportCbBiddingProject()
const { data: productListDataOfSupplier, isLoading: isGetProductListOfSupplierLoading } = useGetProductListOfSupplier(getProductListOfSupplierParams)
const { mutate: deleteProductOfProject } = useDeleteProductOfProject()

const isSubmitLoading = computed(() => isEditProductQuantityOfProjectPending.value)
const isExportLoading = computed(() => isExportZbTenderProjectPending.value || isExportCbBiddingProjectPending.value)

// #region Product Table
const isProductTableLoading = computed(() => isGetProductListOfProjectLoading.value || isGetProductListOfSupplierLoading.value)
const productTableRef = ref<VxeTableInstance>()
const productTableData = ref<any[]>([])

const productGridOptions = {
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'categoryName', title: '组合商品类目', width: 270 },
        { field: 'productName', title: '组合商品名称', width: 270 },
        { field: 'excludingRatePrice', formatter: formatPrice, title: '除税价' },
        { field: isCheckSupplier.value ? 'rate' : 'rateDisplay', title: '税率', width: 80 },
        { field: 'ratePrice', formatter: formatPrice, title: '含税价' },
        { field: 'quantity', slots: { default: 'quantity' }, title: '数量' },
        { field: 'totalPrice', formatter: formatPrice, title: '不含税总价' },
        { field: 'unitPrice', slots: { default: 'unit_price' }, title: '单价汇总' },
        {
            slots: { default: 'operation' },
            title: '操作',
            visible: !(isCheckSupplier.value || route.query.type === 'see'),
            width: 100,
        },
    ],
    headerRowClassName: 'text-[#86909C] text-[14px]',
    height: undefined,
}

function formatPrice({ cellValue }) {
    return Number.isNaN(Number.parseFloat(cellValue)) ? '' : `${cellValue}元`
}
// #endregion

// #region UI Listener
function onChooseProductBtnClick() {
    showChooseProduct.value = true
}

function onCheckDetailBtnClick(row: any) {
    toCheckProductId.value = row.productId
    showCheckProduct.value = true
}

function onDeleteBtnClick(row: any) {
    createConfirmModal({
        content: '确定要删除该组价商品吗？',
        onSuccess: () => {
            deleteProductOfProject(row.id, {
                onSuccess() {
                    ElMessage.success('操作成功')
                },
            })
        },
        title: '提示',
    })
}

function onBackBtnClick() {
    router.back()
}

function onSaveBtnClick(isPubilc = false) {
    if (!productTableData.value.length) {
        ElMessage.warning('请选择组合商品')
        return
    }
    const params = productTableData.value.map((item: any) => ({
        id: item.id,
        quantity: item.quantity,
    }))

    const isEnpty = productTableData.value.some((v: any) => !v.quantity)
    if (isEnpty && isPubilc) {
        ElMessage.warning('数量不得为0')
        return
    }

    editProductQuantityOfProject(params, {
        onSuccess() {
            if (isPubilc) {
                doPublic()
            }
            else {
                ElMessage.success('操作成功')
            }
        },
    })
}

const { mutate: mutatePublic } = useDoPubilc()
function doPublic() {
    mutatePublic(projectId, {
        onSuccess() {
            ElMessage.success('操作成功')

            router.back()
        },
    })
}

function onProductQuantityChange(row: any) {
    row.quantity = Math.abs(Number.parseInt(row.quantity))
}

function exportFile() {
    if (!productTableData.value.length) {
        ElMessage.warning('暂无数据')
        return
    }

    if (route.query?.supplierId) {
        // 投标端导出
        exportCbBiddingProject({ projectId, supplierId: route.query.supplierId })
    }
    else if (projectId) {
        exportZbTenderProject(projectId)
    }
}
// #endregion

watchEffect(() => {
    productTableData.value = cloneDeep((isCheckSupplier.value
        ? productListDataOfSupplier.value?.productPriceList
        : productListDataOfProject.value?.projectProductVOList) || [])
    totalPrice.value = isCheckSupplier.value ? productListDataOfSupplier.value?.totalPrice : productListDataOfProject.value?.totalPrice
    isPublished.value = isCheckSupplier.value ? true : productListDataOfProject.value?.projectStatus === PRICING_PROJECT_STATUS_MAP.PUBLISHED
})
</script>

<template>
    <el-container class="h-full">
        <el-main class="bg-white">
            <el-row>
                <el-col :span="24"
                        class="!flex"
                >
                    <span class="text-[20px] font-semibold">工程分项价格清单表</span>

                    <el-button v-if="!isPublished"
                               type="primary"
                               class="ml-40"
                               @click="onChooseProductBtnClick"
                    >
                        选择组合商品
                    </el-button>
                </el-col>

                <el-col :span="24"
                        class="mt-20"
                >
                    <div>
                        <SearchTable v-bind="productGridOptions"
                                     ref="productTableRef"
                                     :loading="isProductTableLoading"
                                     :data="productTableData"
                        >
                            <template #quantity="{ row }">
                                <span v-if="isCheckSupplier || route.query.type === 'see'">{{ row.quantity }}</span>

                                <el-input v-else
                                          v-model="row.quantity"
                                          placeholder="请输入数量"
                                          type="number"
                                          @change="onProductQuantityChange(row)"
                                />
                            </template>

                            <template #unit_price="{ row }">
                                <el-button text
                                           type="primary"
                                           class="!p-4"
                                           @click="onCheckDetailBtnClick(row)"
                                >
                                    查看
                                </el-button>
                            </template>

                            <template #operation="{ row }">
                                <el-button text
                                           class="!p-4 !text-[#86909C]"
                                           @click="onDeleteBtnClick(row)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </SearchTable>
                    </div>
                </el-col>

                <el-col :span="4"
                        class="mt-50 justify-center !flex"
                >
                    <span class="mr-8 leading-32">不含税合计</span>

                    <el-input :model-value="totalPrice"
                              placeholder=""
                              class="flex-1"
                              disabled
                    >
                        <template #suffix>
                            元
                        </template>
                    </el-input>
                </el-col>

                <el-col :span="24"
                        class="mt-50 justify-center !flex"
                >
                    <el-button @click="onBackBtnClick">
                        返回
                    </el-button>

                    <SubmitBtn type="primary"
                               :loading="isExportLoading"
                               @click="exportFile"
                    >
                        导出
                    </SubmitBtn>

                    <SubmitBtn v-if="!isPublished"
                               type="primary"
                               :loading="isSubmitLoading"
                               @click="onSaveBtnClick"
                    >
                        保存
                    </SubmitBtn>

                    <SubmitBtn v-if="!isPublished"
                               type="primary"
                               :loading="isSubmitLoading"
                               @click="onSaveBtnClick(true)"
                    >
                        保存并发布
                    </SubmitBtn>
                </el-col>
            </el-row>
        </el-main>
    </el-container>

    <ChooseProduct v-if="showChooseProduct"
                   v-model:visible="showChooseProduct"
                   :project-id="projectId"
    />

    <CheckProduct v-if="showCheckProduct"
                  v-model:visible="showCheckProduct"
                  :product-id="toCheckProductId"
    />
</template>

<style scoped lang="scss">
:deep(.vxe-table--body-wrapper) {
    min-height: 48px !important;
}

:deep(.vxe-grid--toolbar-wrapper) {
    display: none;
}
</style>
